package com.hyyt.shopjsp.common.controller;

import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import com.hyyt.shopjsp.util.upload.FileTypeUtil;
import com.hyyt.shopjsp.util.upload.FileUploadUtil;
import com.hyyt.shopjsp.util.upload.UploadResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 *
 * @Description
 * @Location com.hyyt.shopjsp.common.controller.UpLoadFileController
 * @author 张丁方
 * @CreateTime 2017-03-22 18:19
 */
@Controller
@RequestMapping("/back/upload")
public class UploadFileController extends BaseController {

    /**
     * 备注：后台使用
     *
     * 图片上传
     * @return map photoUrl	上传文件后的路径（用于数据库URL存储）
     * @webservice url:192.168.1.103/ws/upload/uploadImageFile
     */
    @RequestMapping(value = "/uploadImageFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg uploadImageFile(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        UploadResult uploadResult = new UploadResult();
        long  startTime=System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile imageInfo=multiRequest.getFile(iter.next().toString());
                //文件对象不为空
                if (Utils.objectIsNotEmpty(imageInfo)) {
                    uploadResult = FileUploadUtil.uploadImagesFile(imageInfo, imageInfo.getOriginalFilename(),request.getParameter("subSysFolderName"),request.getParameter("imageInfoPath"));
                }
            }

        }
        map.put("photoUrl", uploadResult.getFileUrl());
        map.put("uploadFileVisitRoot", RedisDataReadUtil.getSysConfig("uploadFileVisitRoot"));
        return  ResultMsg.create(uploadResult.getSuccess(),uploadResult.getMsg(), FastJsonUtils.collectToString(map));
    }

    /**
     * 备注：后台使用
     *
     * 视频上传
     * @return map videoUrl	上传文件后的路径（用于数据库URL存储）
     * @webservice url:192.168.1.103/ws/upload/uploadVideoFile
     */
    @RequestMapping(value = "/uploadVideoFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg uploadVideoFile(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        UploadResult uploadResult = new UploadResult();
        long  startTime=System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile videoInfo=multiRequest.getFile(iter.next().toString());
                map.put("videoSize", String.valueOf(videoInfo.getSize()));
                //文件对象不为空
                if (Utils.objectIsNotEmpty(videoInfo)) {
                    uploadResult = FileUploadUtil.uploadVideoFile(videoInfo, videoInfo.getOriginalFilename(),multiRequest.getParameter("subSysFolderName"),multiRequest.getParameter("videoInfoPath"));
                }
            }
        }
        map.put("videoUrl", uploadResult.getFileUrl());
        map.put("uploadFileVisitRoot", RedisDataReadUtil.getSysConfig("uploadFileVisitRoot"));
        return  ResultMsg.create(uploadResult.getSuccess(),uploadResult.getMsg(), FastJsonUtils.collectToString(map));
    }


    /**
     * 备注：后台使用
     *
     * 删除图片上传
     * @param fileStoreUrl 文件存储的路径
     * @webservice url:192.168.1.103/ws/upload/deleteFile
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteFile(@RequestParam String fileStoreUrl) {
        boolean isSuccess= FileUploadUtil.deleteFile(fileStoreUrl);
        return ResultMsg.create(isSuccess);
    }

    /**
     * 备注：后台使用
     *
     * ueditor 上传图片
     * @param upfile
     * @param subSysFolderName 子系统目录
     * @param imageInfoPath 图片分支路径
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/imgUploadByUeditor")
    public Map<String, Object> imgUploadByUeditor (MultipartFile upfile, String subSysFolderName, String imageInfoPath){
        Map<String, Object> params = new HashMap<String, Object>();
        try{
            UploadResult uploadResult = new UploadResult();
            //文件对象不为空
            if (Utils.objectIsNotEmpty(upfile)) {
                uploadResult = FileUploadUtil.uploadImagesFile(upfile, upfile.getOriginalFilename(), subSysFolderName,imageInfoPath);
            }
            params.put("state", "SUCCESS");
            params.put("url", uploadResult.getFileUrl());
            params.put("size", upfile.getSize());
            params.put("original", uploadResult.getFileUrl());
            params.put("type", upfile.getContentType());
        } catch (Exception e){
            params.put("state", "ERROR");
        }
        return params;
    }

}


